package com.phiture.erp.finance.core.factory;

import com.phiture.erp.finance.common.enums.ErpFinanceStatementTypeEnum;
import com.phiture.erp.finance.core.handler.ErpFinanceStatementHandler;
import com.phiture.erp.finance.core.pojo.dto.ErpGenerateFinanceStatementDTO;
import com.phiture.erp.finance.core.pojo.dto.ErpRemoveFinanceStatementDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author YH
 * @date 2025-05-06-10:40
 */

@Component
public class ErpFinanceStatementFactory {
    private final Map<String, ErpFinanceStatementHandler> strategyMap;

    @Autowired
    public ErpFinanceStatementFactory(List<ErpFinanceStatementHandler> handlers) {
        this.strategyMap = handlers.stream()
                .collect(Collectors.toMap(
                        ErpFinanceStatementHandler::getStrategyType,
                        Function.identity()
                ));
    }

    public boolean generateFinanceStatement(ErpGenerateFinanceStatementDTO dto) {
        return getHandler(dto.getType()).generate(dto);
    }

    public void removeFinanceStatement(ErpRemoveFinanceStatementDTO dto) {
        getHandler(dto.getType()).remove(dto);
    }

    public ErpFinanceStatementHandler getHandler(Integer type) {
        String strategyType = ErpFinanceStatementTypeEnum.fromType(type).getVal();
        ErpFinanceStatementHandler handler = strategyMap.get(strategyType);
        if (handler == null) {
            throw new IllegalArgumentException(
                    String.format("Invalid ERP FINANCE STATEMENT strategy type: %s. Available: %s",
                            strategyType,
                            String.join(", ", strategyMap.keySet()))
            );
        }
        return handler;
    }
}
